package com.ycsj.goldmedalnewconcept.teacher.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.TDialogManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.view.flowlayout.FlowLayout;
import com.ycsj.common.view.flowlayout.TagAdapter;
import com.ycsj.common.view.flowlayout.TagFlowLayout;
import com.ycsj.common.view.scroll.MyListView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.TkKeys;
import com.ycsj.goldmedalnewconcept.common.bean.SubListBean;
import com.ycsj.goldmedalnewconcept.common.bean.TkItemBean;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.RvWordFormAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.InputWordInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.TkInputInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据所给词适当形式填空
 * Created by Administrator on 2018/9/3 0003.
 */

public class TkSentenceCompleFragment extends LazyBaseFragment {

    //页面对象
    private TkItemBean info;

    //题目类型
    private TextView tvType;

    //标题
    private TextView tvTitle;

    //题目内容
    private TextView tvContent;

    //输入单词的列表
    private MyListView lv;
    private RvWordFormAdapter adapter;

    //已完成跳转进入需要展示的布局部分
    private LinearLayout ll_show_answer;

    //作答
    private LinearLayout ll_stu_answer;


    //全校正确率
    private LinearLayout ll_qxzql;

    //展示你选择的答案的ListView
    private MyListView lv_own_answer;

    //展示正确答案的ListView
    private MyListView lv_right_answer;

    //展示你选择的答案的流式布局
    private TagFlowLayout fl_answer;

    //展示你选择的答案的流式布局
    private TagFlowLayout fl_right_answer;

    //解析
    private TextView tv_parse_answer;

    //全校正确率
    private TextView tv_qxzql;

    //已完成状态下自己作答的全部单词的集合
    private String[] ownAnswers;
    private String[] rightList;

    //以完成状态下的解析
    private String explain;

    //默认的用于替换用户输入答案的值
    public static final String DEFAULTCONTENT = "___";

    //用于保存用户输入的内容,初始值为服务器返回的_____5个下划线
    private Map<Integer, String> inputContent;

    //使用正则表达式切割题干后的字符串集合
    private String[] sentences;

    //切割答案后的字符串集合
    private String[] options;

    //切割题目的正则表达式
    public static final String reg = "_{1,}[0-9a-zA-Z_]+_{1,}";
//    public static final String reg = "__{1,}";

    //序号标记
    private String[] letters = {"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩"};

    private List<InputWordInfo> oldDatas;

    //学生做题0  1学生查看解析 2老师查看题和解析-有人做(全校正确率和小题正确率都显示) 3(习题分析)老师查看题和解析-没人做,对应查看单题
    private String type;

    //当前大题在整个题目中所处的位置
    private int currPos;

    public static final TkSentenceCompleFragment newInstance(TkItemBean item, String type, int currPos) {
        TkSentenceCompleFragment tkWordFormInBlankFragment = new TkSentenceCompleFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", item);
        bundle.putSerializable("type", type);
        bundle.putInt("currpos", currPos);
        tkWordFormInBlankFragment.setArguments(bundle);
        return tkWordFormInBlankFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_word_form_in_blank;
    }


    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);

        //获取页面对象
        initIntent();

        //初始化视图
        initView(view);

        //初始化底部的列表数据
        initRv();

    }


    /**
     * 获取页面对象
     */
    private void initIntent() {
        info = (TkItemBean) getArguments().getSerializable("data");

        LogUtils.iTag("test", "获取的当前小题是:*****" + GsonUtil.objectToJson(info));

        type = (String) getArguments().getSerializable("type");

        //获取当前大题在整个题目中所处的位置
        currPos = getArguments().getInt("currpos");

        //获取解析,注意:这里的解析只有一个
        explain = info.getAnalysis();

    }

    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        fl_answer = view.findViewById(R.id.fl_answer);
        fl_right_answer = view.findViewById(R.id.fl_right_answer);

        tvType = view.findViewById(R.id.tv_type);
        tvTitle = view.findViewById(R.id.tv_title);
        tvContent = view.findViewById(R.id.tv_content);
        tv_qxzql = view.findViewById(R.id.tv_qxzql);

        lv = view.findViewById(R.id.lv);
        //已完成跳转进入需要展示的布局部分
        ll_show_answer = view.findViewById(R.id.ll_show_answer);
        ll_stu_answer = view.findViewById(R.id.ll_stu_answer);

        ll_qxzql = view.findViewById(R.id.ll_qxzql);

        tv_parse_answer = view.findViewById(R.id.tv_parse_answer);

        //获取标题的内容
        if (TextUtils.isEmpty(info.getN_topic_name())) {
            tvType.setText(info.getN_type_name());
        } else {
            tvType.setText(info.getN_type_name() + "-" + info.getN_topic_name());
        }
        //题目
        tvContent.setText(info.getContent());
        if ("1".equals(type)) {
            //学生已答题查看解析
            lv.setEnabled(false);
            ll_show_answer.setVisibility(View.VISIBLE);
            ll_qxzql.setVisibility(View.GONE);
            //设置已完成状态下用户的数据
            initHasCompetedData();
        } else if ("0".equals(type)) {
            //学生未答题
            if ("0".equals(AccountUtils.getRole(getActivity()))) {
                //未完成列表选项可以点击
                lv.setEnabled(true);
            } else {
                //家长不可点击
                lv.setEnabled(false);
            }

            ll_show_answer.setVisibility(View.GONE);
            initHasCompletedData();
        } else if ("3".equals(type)) {
            //查看单题或者老师查看学生解析(没人作答)
            lv.setEnabled(false);
            ll_qxzql.setVisibility(View.GONE);
            ll_show_answer.setVisibility(View.VISIBLE);
            ll_stu_answer.setVisibility(View.GONE);
            //设置已完成状态下用户的数据
            initHasCompetedData();
        } else if ("2".equals(type)) {
            //老师查看学生解析(有人作答)
            lv.setEnabled(false);
            ll_show_answer.setVisibility(View.VISIBLE);
            ll_qxzql.setVisibility(View.VISIBLE);
            initHasCompetedData();
        }
    }


    /**
     * 初始化列表数据
     */
    private void initRv() {
        //创建数据集合
        oldDatas = new ArrayList<>();
        List<SubListBean> rightAnswers = info.getSub_list();

        //作答内容
        if (rightAnswers.get(0).getStu_option() != null) {

            ownAnswers = rightAnswers.get(0).getStu_option().split("∩");
        }
        rightList = rightAnswers.get(0).getOption().split("∩");

        for (int i = 0; i < rightList.length; i++) {
            InputWordInfo info = new InputWordInfo();
            info.flag = (1 + i) + "";
            info.rightAnswer = rightList[i];
            if ("1".equals(type)) {
                // 已完成状态
                if (i < ownAnswers.length) {
                    info.word = ownAnswers[i];
                }
            }
            oldDatas.add(info);
        }

        adapter = new RvWordFormAdapter(getContext(), oldDatas, R.layout.tk_rv_item_form_blank);
        lv.setAdapter(adapter);

        if ("0".equals(type)) {

            //点击事件弹框输入内容
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, final int pos, long l) {

                    TDialogManager.show(getContext(), getActivity().getSupportFragmentManager(), R.layout.teacher_app_pop_input_read_essay, 0.3f, new OnBindViewListener() {
                        @Override
                        public void bindView(BindViewHolder viewHolder) {
                            viewHolder.setText(R.id.tv_pop_content, "请输入答案");
                            EditText etInput = viewHolder.getView(R.id.et_input);
                            etInput.setFilters(new InputFilter[]{new MaxTextLengthFilter(151)});
                        }
                    }, new OnViewClickListener() {
                        @Override
                        public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                            switch (view.getId()) {
                                case R.id.tv_cancel:
                                    TDialogManager.dismiss();
                                    break;
                                case R.id.tv_ok:
                                    //获取输入的内容
                                    EditText etInput = viewHolder.getView(R.id.et_input);
                                    String content = etInput.getText().toString().trim();
                                    if (TextUtils.isEmpty(content)) {
                                        ToastUtils.showShort("您还未输入单词");
                                        return;
                                    } else {
                                        TDialogManager.dismiss();
                                        oldDatas.get(pos).word = content;
                                        adapter.notifyDataSetChanged();
                                        //将输入的答案通过EventBus回传TkMainActivity进行更新
                                        //currPos对应的每个大题的小题的位置
                                        int choosePos = 0;
                                        //用户选的输入的单词
                                        String chooseAnswer = getSelfContent();

                                        //判断题目是否完成
                                        if (IsFinish()) {
                                            //是否如正确
                                            boolean chooseResult = false;

                                            //判断作答是否正确
                                            chooseResult = SavaContent();

                                            Log.i("test", "chooseResult=" + chooseResult);
                                            BusInfo busInfo = new BusInfo();
                                            busInfo.tkMsg = TkKeys.TKMsg;
                                            busInfo.tkChoosePos = choosePos;
                                            busInfo.tkChooseAnswer = chooseAnswer;
                                            busInfo.tkChooseResult = chooseResult;
                                            EventBus.getDefault().post(busInfo);
                                        }
                                    }
                                    break;
                            }
                        }

                    }, R.id.tv_cancel, R.id.tv_ok);
                }
            });
        }
    }

    /**
     * 拼接所有题目的答案判断正确
     */
    private boolean SavaContent() {
        boolean res = false;
        String content = "";
        for (int i = 0; i < oldDatas.size(); i++) {
            if (i != oldDatas.size() - 1) {
                content += oldDatas.get(i).word + "∩";
            } else {
                content += oldDatas.get(i).word;
            }
        }

        Log.i("test", "Option=" + info.getSub_list().get(0).getOption());
        Log.i("test", "content=" + content);
        if (content.equals(info.getSub_list().get(0).getOption())) {
            res = true;
        }

        if (isRight(content, info.getSub_list().get(0).getOption())) {
            res = true;
            Log.i("test", "isRight=" + res);
        }
        return res;
    }


    /**
     * 拼接所有题目的答案
     */
    private String getSelfContent() {
        String content = "";
        for (int i = 0; i < oldDatas.size(); i++) {
            if (i != oldDatas.size() - 1) {
                content += oldDatas.get(i).word + "∩";
            } else {
                content += oldDatas.get(i).word;
            }
        }

        return content;
    }

    /**
     * 判断题目是否做完
     */
    private boolean IsFinish() {
        boolean res = true;
        for (int i = 0; i < oldDatas.size(); i++) {
            if (TextUtils.isEmpty(oldDatas.get(i).word)) {
                res = false;
                break;
            }
        }
        return res;
    }


    /**
     * 判断答案是否正确
     */
    private boolean isRight(String chooseAnswer, String rightAnswer) {
        boolean res = false;
        String[] rightArrays = rightAnswer.split("/");

        for (int i = 0; i < rightArrays.length; i++) {
            if ((chooseAnswer.equals(rightArrays[i].trim())) ||
                    (chooseAnswer.equals("/") && rightArrays[i].trim().equals("*"))) {
                res = true;
                break;
            }
        }
        return res;
    }


    /**
     * 判断所有填空题目是否做完
     */
    private boolean isEmptyAnswer() {

        for (int i = 0; i < oldDatas.size(); i++) {
            if (TextUtils.isEmpty(oldDatas.get(i).word)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 初始化你的作答,正确答案,答案正确率和解析
     * 需要通过用户是否是已完成和未完成的状态来确定该部分的视图显示与隐藏,同时设置数据的数据源不一样
     * 该设置需要取已完成状态的数据源集合
     */
    private void initHasCompetedData() {

        //切割每个填空的答案
        options = info.getSub_list().get(0).getOption().split("∩");

        List<SubListBean> rightsAnswers = info.getSub_list();

        final LayoutInflater mInflater = LayoutInflater.from(getActivity());

        if ("1".equals(type)) {
            if (info.getSub_list().get(0).getStu_option() != null) {

                ownAnswers = info.getSub_list().get(0).getStu_option().split("∩");


                //创建你的作答的数据
                final List<TkInputInfo> selfDatas = new ArrayList<>();
                for (int i = 0; i < ownAnswers.length; i++) {
                    TkInputInfo info = new TkInputInfo();
                    info.index = "(" + (i + 1) + ")";
                    info.content = ownAnswers[i];
                    selfDatas.add(info);
                }


//                LogUtils.iTag("test", "学生的作答是：****" + GsonUtil.listToJson(selfDatas));

                //自己的答案选项
                fl_answer.setAdapter(new TagAdapter<TkInputInfo>(selfDatas) {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public View getView(FlowLayout parent, int position, TkInputInfo tkInputInfo) {
                        TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_ownanswer,
                                fl_answer, false);

//                        LogUtils.iTag("test", "学生的作答是：****" + selfDatas.get(position).index + selfDatas.get(position).content);
//                        tv.setText(Html.escapeHtml(selfDatas.get(position).index + selfDatas.get(position).content));
                        tv.setText(selfDatas.get(position).index + selfDatas.get(position).content);

                        return tv;
                    }
                });

                //正确答案的数据
                final List<TkInputInfo> rightDatas = new ArrayList<>();
                for (int i = 0; i < options.length; i++) {
                    TkInputInfo info = new TkInputInfo();
                    info.index = "(" + (i + 1) + ")";
                    info.content = options[i];
                    rightDatas.add(info);
                }

                fl_right_answer.setAdapter(new TagAdapter<TkInputInfo>(rightDatas) {
                    @Override
                    public View getView(FlowLayout parent, int position, TkInputInfo tkInputInfo) {
                        TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_rightanswer,
                                fl_right_answer, false);
                        tv.setText(rightDatas.get(position).index + rightDatas.get(position).content);
                        return tv;
                    }
                });
            }
        }


        //设置正确率
        if ("2".equals(type)) {
            tv_qxzql.setText(info.getSub_list().get(0).getYes_pro());
        }


        //正确答案的数据
        final List<TkInputInfo> rightDatas = new ArrayList<>();
        for (int i = 0; i < options.length; i++) {
            TkInputInfo info = new TkInputInfo();
            info.index = "(" + (i + 1) + ")";
            info.content = options[i];
            rightDatas.add(info);
        }


        fl_right_answer.setAdapter(new TagAdapter<TkInputInfo>(rightDatas) {
            @Override
            public View getView(FlowLayout parent, int position, TkInputInfo tkInputInfo) {
                TextView tv = (TextView) mInflater.inflate(R.layout.teacher_class_tv_rightanswer,
                        fl_right_answer, false);
                tv.setText(rightDatas.get(position).index + rightDatas.get(position).content);
                return tv;
            }
        });


        //设置解析
        tv_parse_answer.setText(explain);
    }


    /**
     * 处理数据
     */
    private void initHasCompletedData() {

        //题干内容,服务器返回
        String questionContent = info.getContent();

        //将服务器返回的题干使用正则表达式切割
        sentences = questionContent.split(reg);

        //切割每个填空的答案
        options = info.getSub_list().get(0).getOption().split("∩");

        //初始化内容
        inputContent = new LinkedHashMap<>();

        for (int i = 0; i < options.length; i++) {
            inputContent.put(i, DEFAULTCONTENT);
        }

        //创建序号的集合
        String[] indexNums = new String[inputContent.size()];

        for (int i = 0; i < inputContent.size(); i++) {
            //这里控制是否显示每空的序号
            indexNums[i] = letters[i];
        }

        //拼接需要重新显示的字符串
        String content = "";
        if (sentences.length == inputContent.size()) {
            //题干内容以__结尾,切割的数组长度和填空的位置一样
            for (int i = 0; i < sentences.length; i++) {
                content += sentences[i] + indexNums[i] + inputContent.get(i);
            }

        } else {
            //题干内容不以__结尾,切割的字符串数组长度比需要填空的位置多一个
            for (int i = 0; i <= sentences.length - 2; i++) {
                //sentences的是8,但是inputContent的长度是7
                content += sentences[i] + indexNums[i] + inputContent.get(i);
            }
            content += sentences[sentences.length - 1];
        }

        //计算文字变色和添加下划线
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder(content);

        for (int i = 0; i < indexNums.length; i++) {

            //序号需要变色的起始位置
            int start = 0;
            int end = 0;

            for (int j = 0; j <= i; j++) {
                start += sentences[j].length();
            }

            for (int k = 0; k <= i - 1; k++) {
                start += indexNums[k].length();
                start += inputContent.get(k).length();
            }

            end = start + indexNums[i].length();

            //设置变色
            stringBuilder.setSpan(new ForegroundColorSpan(Color.parseColor("#EC8628")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            //需要添加下划线的起始位置
            int clickStart = 0;
            int clikcEnd = 0;

            for (int j = 0; j <= i; j++) {
                clickStart += sentences[j].length();
                clickStart += indexNums[j].length();
            }

            for (int k = 0; k <= i - 1; k++) {
                clickStart += inputContent.get(k).length();
            }

            clikcEnd = clickStart + inputContent.get(i).length();

            //设置下划线和点击变色的文字位置
            stringBuilder.setSpan(new TkSentenceCompleFragment.TextClick() {
                @Override
                public void onClick(View view) {
                }
            }, clickStart, clikcEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        //设置文字
        tvContent.setText(stringBuilder);

    }

    /**
     * 点击事件
     */
    private abstract class TextClick extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(true);
            ds.setStrokeWidth(3);
            ds.setColor(Color.parseColor("#EC8628"));
        }
    }
}
